<template>
	<div class="write-page">
		<div class="write-icon">
			<img src="../assets/img/hexiao.png" alt="" v-if="!isScanning">
			<qrcode-stream v-if="isScanning" @decode="handleDecode" @init="onInit" @stop="onStop"></qrcode-stream>
		</div>
		<div class="hint">
			<div class="hint-title">扫描券码 一键核销</div>
			<div class="subheader">降低核销门槛 低成本留存优质客户</div>
			<van-button @click="startScanning" class="scan-btn" block type="info">扫码核销</van-button>
		</div>
	</div>
</template>

<script>
	import {
		QrcodeStream
	} from 'vue-qrcode-reader';
	import axios from 'axios';
	import {
		Button,
		Toast,
		Dialog
	} from 'vant'
	export default {
		data() {
			return {
				baseUrl: 'http://81.70.216.192:19130/spacelink',
				isScanning: false,
				scanResult: '',
				shopid: this.$route.query.shopid
			}
		},
		methods: {
			startScanning() {
				this.isScanning = true;
			},
			handleDecode(result) {
				this.scanResult = result;
				this.writeOff()
				this.isScanning = false; // 扫描成功后自动停止
			},
			writeOff() {
				axios({
					url: this.baseUrl+ '/api/h5shop/query/qrcode',
					params: {
						qrcode: this.scanResult,
						shopid: this.shopid
					},
					method: 'GET'
				}).then(res => {
					let data = res.data
					if(data.code == 200) {
						Dialog.alert({
						  message: data.msg
						}).then(() => {
						  // on close
						});
					} else {
						Toast(data.msg)
					}
				})

			},
			onInit(promise) {
				promise.catch(error => {
					console.log(error)
					if (error.name === 'NotAllowedError') {
						Toast('请允许访问摄像头以进行扫码。');
					} else if (error.name === 'NotFoundError') {
						Toast('未找到二维码扫描设备。');
					} else {
						Toast('初始化二维码扫描时发生错误: ' + error.message);
					}
					this.isScanning = false;
				});
			},
			onStop() {
				this.isScanning = false;
			},
		},
		components: {
			QrcodeStream,
			'van-button': Button
		}
	}
</script>

<style lang="less">
	.write-page {
		height: 100vh;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding: 0.3rem;

		.write-icon {
			width: 5rem;
			height: 5rem;
			margin-bottom: 2rem;

			img {
				width: 100%;
				height: 100%;
				object-fit: contain;
			}
		}

		.hint {
			width: 100%;
		}

		.hint-title {
			margin-bottom: 0.3rem;
			font-size: .5rem;
			color: #333;
			text-align: center;
		}

		.subheader {
			font-size: .24rem;
			color: #999;
			text-align: center;
		}

		.scan-btn {
			margin-top: 0.6rem;
		}
	}
</style>